<!--
*@Author: QWP
*@Description: 用车申请编辑
*@Date: 2024-07-08 17:04:38
-->
<template>
  <u-dialog v-bind="$attrs"
    :confirmLoading="loading"
    :destroyOnClose="true"
    :hideBtns="hideBtns"
    @submit="submit"
    @close="dialogClose">
    
    <a-layout class="f-h-100">
      <a-layout-content class="s-bg-white"
        style="overflow: auto">
        <u-flow-tab activeKey="1"
          :show="isValue(form.status)"
          :processId="current['processintsid']"
          :params="{ type: 'send_car_info', ...current }"
          :isAudit="form.status == 2"
          :isAuditPage="route.params.pType == '2'"
          v-bind="$attrs"
          ref="auditRef">
          <a-tab-pane key='1' tab="基本信息">
            <a-space  direction="vertical">
              <u-busi-card title="基本信息"
                :bordered="false">
                <u-form :elements="formEls"
                  :model="form"
                  :gutter="0"
                  :loading="loading"
                  :disabled="route.params.pType == 3"
                  @formChange="changeForm"
                  ref="formRef">
                </u-form>
              </u-busi-card>
              <u-busi-card title="司机信息"
                :bordered="false"
                v-if="['3'].includes(route.params.pType + '')">
                <u-edit-table :columns="driverCol"
                  :data="driverData"
                  :loading="loading"
                  :scroll="{ y: '300px' }"
                  @editChange="tabEdit">
                </u-edit-table>
              </u-busi-card>
            </a-space>
          </a-tab-pane>
        </u-flow-tab>
      </a-layout-content>
    </a-layout>

    <template #footerBefore>
      <template v-if="!form['status'] || ['1', '4'].includes(form['status'] + '')">
        <u-icon-button itype="save" @click="submit('up')">保存并上报</u-icon-button>
      </template>
      <template v-if="route.params.pType == '2' && form['status'] == '2'">
        <u-icon-button itype="approve" @click="auditAbout('2')">批准</u-icon-button>
        <u-icon-button itype="close" @click="auditAbout('3')">退回</u-icon-button>
      </template>
    </template>
  </u-dialog>
</template>

<script lang='ts' setup>
import { ref, reactive, computed, onMounted, h, useAttrs, watch } from 'vue' 
import { useLoginStore,  useBaseStore } from '@/store'
import { storeToRefs } from 'pinia';
import { useRoute, useRouter } from 'vue-router'
import { _IFormEl, _IExtra } from '@/src/components/common/form/interface';
import { FormInstance, FormItemProps } from 'ant-design-vue';
import { HomeOutlined, FileTextOutlined, UploadOutlined } from '@ant-design/icons-vue';
import { TreeProps } from 'ant-design-vue/es/vc-tree';
import { ColumnProps } from 'ant-design-vue/es/table';
import { _IColumnProps } from '@/components/common/tableEdit/interface.ts'
import { fileCols } from '@/common/model/fileCols'
import { depts, users, regions, isSel } from '@/common/model/base'
import { alertC, messageC, nullC, isValue } from '@/util/common';
import { disabledDateC } from '@/util/format.ts'
import { cloneDeep } from 'lodash'
import { useAuditAbout, IAuditParams } from '@/hooks/useAudit'
import * as sendApi from '@/service/administration/sendCar'
import * as driverApi from '@/service/administration/driver'
import * as userApi from '@/service/system/user'
import * as deptApi from '@/service/system/dept'
import * as auditApi from '@/service/audit'
import dayjs from 'dayjs';
const props = withDefaults(
  defineProps<{
    current?: object,
  }>(),
  {
    current: {}
  }
)
const route = useRoute()
const attrs = useAttrs()
const { userInfo } = storeToRefs(useLoginStore())
const { APPROVEDMODEL, deptData, deptUsers } = storeToRefs(useBaseStore())
const emits = defineEmits(['success'])

const hideBtns = computed(() => {
  // 派车确认
  if(route.params.pType == '3') {
    return []
  }
  if(['2'].includes(route.params.pType + '') || ['2', '3'].includes(form.value['status'] + '')) {
    return ['submit']
  }
})

// 是否是审核页面
const isAudit = computed(() => route.params.pType == '2')

// 是否该我审核
const isAuditMe = computed(() => userInfo['userId'] == currentData.value["fkaudituserid"])

// 基础数据
const baseData = reactive({
  drivers: [],
  cpdata: [],
  approveCars: APPROVEDMODEL.value
})

const userDatas = computed(() => {
  let info = deptUsers.value.find(i => i.keyid == form.value.vehicledeptid) || {};
  return info['children'] || []
})

// 表单信息
const loading = ref<boolean>(false)
const auditRef = ref<FormInstance>()
const formRef = ref<FormInstance>()
const currentData = ref<object>()
const form = ref({})
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: '120px',
  colon: false
}
const formEls: Array<_IFormEl> = reactive([
  { label: '申请人', key: 'applicant', col: { span: 8,}, element: 'input', 
    formItemProps: { ...formItemProps,},
    componentProps: { disabled: true } 
  },
  { label: '申请人电话', key: 'applicantphone', col: { span: 8 }, element: 'input', 
    formItemProps: { ...formItemProps,},
    componentProps: { disabled: true } 
  },
  { label: '用车人数', key: 'passengernumber', col: { span: 8 }, element: 'number', 
    formItemProps: { ...formItemProps, required: true},
  },
  { label: '用车部门', key: 'vehicledeptid', col: { span: 8 }, element: 'select', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: { 
      disabled: true,
      options: deptData.value, 
      fieldNames: { label: 'name', value: 'keyid' } 
    } 
  },
  { label: '用车人', key: 'vehicleuserid', col: { span: 8 }, element: 'select', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: { options: userDatas, fieldNames: { label: 'name', value: 'keyid' }}  
  },
  { label: '用车人电话', key: 'vehicleuserphone', col: { span: 8 }, element: 'input', 
    formItemProps: { ...formItemProps, required: true  },
    componentProps: { disabled: true } 
  },
  { label: '用车开始时间', key: 'startdate', col: { span: 8 }, element: 'datepicker', 
    formItemProps: { ...formItemProps, required: true,},
    componentProps: {
      disabledDate: (current: Dayjs) => disabledDateC(current, [
        dayjs().isBefore(dayjs(form.value['startdate'])) ? dayjs() : dayjs(form.value['startdate']), 
        form.value['enddate']], 
        'before')
    }
  },
  { label: '用车结束时间', key: 'enddate', col: { span: 8 }, element: 'datepicker', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      disabledDate: (current: Dayjs) => disabledDateC(current, [ form.value['startdate'] ? form.value['startdate'] : dayjs()], 
        'before')
    }
  },
  { label: '乘车人', key: 'passengers', col: { span: 8 }, element: 'input', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: { placeholder: '乘车人之间用逗号(,)隔开' }  
  },
  { label: '用车范围', key: 'vehclescope', col: { span: 8 }, element: 'select', 
    formItemProps: { ...formItemProps, required: true } ,
    componentProps: { 
      options: [
        {label: '市内', value: '市内'},
        {label: '市外', value: '市外'},
      ]
    }  
  },
  { label: '出发地点', key: 'departure', col: { span: 8 }, element: 'selAddress', 
    formItemProps: { ...formItemProps, required: true } ,  
    componentProps: {
      onChange: (vals, options) => {
        form.value.startAreaCn = (options || []).map(i => i.name).join('/')
      }
    },
  },
  { label: '前往地点', key: 'destination', col: { span: 8 }, element: 'selAddress', 
    formItemProps: { ...formItemProps, required: true } ,  
    componentProps: {
      onChange: (vals, options) => {
        form.value.endAreaCn = (options || []).map(i => i.name).join('/')
      }
    },
  },
  { label: '用车事由', key: 'reason', col: { span: 24 }, element: 'textarea', 
    formItemProps: { ...formItemProps, required: true } 
  },
])

// 初始化表单数据
const initFormValue = () => {
  form.value.applicant= userInfo.value["name"];
  form.value.applicantphone= userInfo.value["tel"] || '1';
  form.value.fkuserid= userInfo.value["userId"];
  form.value.fkusername= userInfo.value["name"];
  form.value.fkdeptid= userInfo.value["deptId"];
  form.value.redeptname= userInfo.value["deptName"];
  form.value.vehicledeptid= userInfo.value["deptId"];
  form.value.vehicledeptname = userInfo.value["deptName"];
  form.value.fkunitsid= userInfo.value["unitId"];
  form.value.unitName= userInfo.value["unitName"];

  // changeForm({ key: 'vehicledeptid', value: form.value.vehicledeptid })
  driverData.value = [];
  getDriver(form.value.vehicledeptid);
}

// 司机信息
const driverData = ref<any[]>([]); 
const driverCol: Array<_IColumnProps> = [
  { title: '车牌号', dataIndex: 'fkvehicleid', minWidth: 150, element: 'select',
    componentProps: { 
      options: computed(() => baseData.cpdata), 
      fieldNames: { label: 'platenumber', value: 'keyid' } 
    }
  },
  { title: '执行司机 ', dataIndex: 'driverid', minWidth: 150, element: 'select',
    componentProps: { 
      options: computed(()=> baseData.drivers), 
      fieldNames: { value: 'driverid', label: 'drivername' },
    }
  },
  { title: '司机电话', dataIndex: 'driverphone', minWidth: 150, element: 'input' },
]; 

// 保存
const submit = async (type?: string) => {
  try {
    await formRef.value.form.validate()
  } catch (error) {
    alertC("请先将必填项填写完毕！")
    return
  }

  // 市内出差
  if(form.value['vehclescope'] == '市内') {
    if(!form.value['destination'].includes('510100000000')) {
      messageC("用车范围为【市内】,请选择正确的前往地!");
      return
    }
  } else if(form.value['vehclescope'] == '市外') {
    if(form.value['destination'].includes('510100000000')) {
      messageC("用车范围为【市外】,请选择正确的前往地!");
      return
    }
  }

  if(route.params.pType == 3) {
    if(driverData.value.length == 0) {
      alertC("请录入司机信息 !");
      return
    }
    let isInput = driverData.value.some(item => ['driverid', 'fkvehicleid'].some(o => !isValue(item[o])))
    if(isInput) {
      alertC("请将车辆和司机信息录入完毕 !");
      return
    }
  }

  const url = form.value.keyid ? "update" : "add";
  let copyform = cloneDeep(form.value);
  if(url == 'add') {
    copyform.status = 1;
  }
  copyform.dispatchdetails = cloneDeep(driverData.value)
  loading.value = true;
  try {
    const data = await sendApi[url](copyform)
    if (data.code == 0) {
      if(type != 'up') {
        messageC(data.msg, "success")
      }
      if(url == 'add') {
        form.value.keyid = data.data['keyid']
        form.value.status = data.data["status"];
      }
      if(type == 'up') {
        await auditAbout('1')
      }
      dialogClose()
      emits("success");
    } else {
      alertC(data.msg, "warning");
    }
  } catch (error) {}
  loading.value = false;
}

// 上报、审核、退回
const auditAbout = async (type: string) => {
  loading.value = true;
  const auditParams: IAuditParams = {
    type: 'send_car_info',
    selDatas: [form.value],
    confirm: false,
    isDialog: false
  }
  try {
    const res = await useAuditAbout(type, auditParams, auditRef)
    if(res.error == 200) {
      dialogClose()
      emits("success");
    } 
  } catch (error) {}
  loading.value = false;
}

// 表单事件
const changeForm = ({ key, value }) => {
  console.log("🚀 ~ changeForm ~ key:", key)
  console.log("🚀 ~ changeForm ~ value:", value)
  switch (key) {
    case "vehicledeptid":
      let deptInfo = deptData.value.find((item) => item.keyid == value) || {}
      form.value.vehicledeptname = nullC(deptInfo['name']);
      form.value.vehicleuserid = "";
      form.value.vehicleusername = "";
      form.value.vehicleuserphone = "";
      driverData.value = [];
      getDriver(value);
      break;
    case "vehicleuserid":
      const userD = userDatas.value.find((item) => item.keyid == value)
      form.value.vehicleusername = userD.name;
      form.value.vehicleuserphone = userD.tel || '1';
      break;
    }
}

// 表格change事件
const tabEdit = ({key, value, row, index}) => {
  if('driverid' == key) {
    let driverInfo = baseData.drivers.find(i => i.driverid == value);
    if(driverInfo) {
      driverData.value.splice(index, 1, { 
        ...row, 
        driverphone: nullC(driverInfo['driverphone']), 
        drivername: nullC(driverInfo['drivername']),
        driverid: value,
      })
    }
  } 
  else if(key == 'fkvehicleid') {
    let carInfo = baseData.cpdata.find(i => i.keyid == value);
    driverData.value.splice(index, 1, { 
      ...row, 
      fkvehicleid: value,
      platenumber: nullC(carInfo['platenumber']),
    })
  }
}

// 获取驾驶员
const getDriver = async(val) => {
  try {
    const data = await driverApi.selectDriverList({ ssdeptId: val })
    baseData.cpdata = data.data.VTVehicle;

    let drivers = {};
    (data.data.VTVehicledriver || []).forEach(i => {
      if(!drivers[i['driverid']]) {
        drivers[i['driverid']] = i
      }
    })
    
    baseData.drivers = Object.values(drivers);
  } catch (error) { }
}

// 回显
const getHxData = async () => {
  loading.value = true;
  try {
    const data = await sendApi.query(form.value.keyid);
    if(data.code == 0) {
      loading.value = false;
      form.value = data.data

      // 回显司机
      getDriver(form.value.vehicledeptid)
      if(form.value['dispatchdetails']) {
        driverData.value = (form.value['dispatchdetails'] || [])
      }
    }
  } catch (error) {}
  loading.value = false;
}

// 弹窗关闭
const dialogClose = () => {
  if(formRef.value) {
    formRef.value.form.resetFields();
  }
  form.value = {}
  driverData.value = []
}

watch(() => attrs.open, (nval, oval) => {
  if (nval == true) {
    initFormValue();
    let keyid = (props.current || {})['keyid'] || ''
    if (keyid != "") {
      form.value.keyid = keyid;
      getHxData();
    }
  }
})
</script>

<style lang='scss' >
</style>